<template>
	<view class="poster-popup" v-if="showPopup">
	</view>
</template>

<script>
	import {
		getUserInfo
	} from '@/api/user.js';
	import {
		getQrCode,
		getQrCodeBag
	} from '@/api/extension.js';

	export default {
		data() {
			return {
				showPopup: false,
				userName: '',
				qrImg: '',
				currentBackground: '',
				screenWidth: uni.getSystemInfoSync().screenWidth,
			};
		},
		computed: {
			canvasHeight() {
				return 400; // 固定高度，可以根据实际情况调整
			}
		},
		methods: {
			async openPopup(bagList) {
				this.currentBackground = bagList[0].posterAddress;
				await this.initData(); // 等待 initData 完成

				// 打印需要绘制的所有元素的信息
				console.log('准备绘制的元素:', {
					currentBackground: this.currentBackground,
					qrImg: this.qrImg,
					userName: this.userName,
					screenWidth: this.screenWidth,
					canvasHeight: this.canvasHeight
				});

				this.showPopup = true;

				this.$nextTick(() => {
					this.mergeImages();
				});
			},
			async initData() {
				try {
					const [qrCodeRes, userInfoRes] = await Promise.all([
						getQrCode(),
						getUserInfo()
					]);

					this.qrImg = qrCodeRes.data;
					this.userName = userInfoRes.data.nickName;

					console.log('初始化数据完成:', {
						qrImg: this.qrImg,
						userName: this.userName
					});
				} catch (err) {
					console.error('初始化数据失败:', err);
				}
			},
			mergeImages() {
				let context = uni.createCanvasContext('canvasOne', this);
				context.clearRect(0, 0, this.screenWidth * 0.7, this.canvasHeight);
				this.downloadAndDrawBackground(context);
			},
			downloadAndDrawBackground(context) {
				uni.downloadFile({
					url: this.currentBackground,
					success: (downloadRes) => {
						if (downloadRes.statusCode === 200) {
							const backgroundTempFilePath = downloadRes.tempFilePath;
							console.log('背景图片下载成功:', backgroundTempFilePath);

							// 在绘制背景之前打印上下文信息
							console.log('绘制背景前的context状态:', context);

							context.drawImage(backgroundTempFilePath, 0, 0, this.screenWidth * 0.7, this
								.canvasHeight);
							context.draw(true, () => { // 强制同步绘制
								console.log('背景绘制完成，准备绘制二维码...');
								this.drawQrCode(); // 下载并绘制二维码，不传递context
							});
						} else {
							console.error('背景图片下载失败:', downloadRes);
						}
					},
					fail: (err) => console.error('背景图片下载失败:', err)
				});
			},
			drawQrCode() {
				let context = uni.createCanvasContext('canvasOne', this); // 每次绘制时重新创建context
				uni.downloadFile({
					url: this.qrImg,
					success: (qrDownloadRes) => {
						if (qrDownloadRes.statusCode === 200) {
							const qrTempFilePath = qrDownloadRes.tempFilePath;
							console.log('二维码下载成功:', qrTempFilePath);

							// 在绘制二维码之前打印上下文信息
							console.log('绘制二维码前的context状态:', context);

							const qrX = this.screenWidth * 0.7 - 80;
							const qrY = this.canvasHeight - 86;
							context.drawImage(qrTempFilePath, qrX, qrY, 60, 60);
							context.draw(true, () => { // 强制同步绘制
								console.log('二维码绘制完成，准备绘制文本...');
								this.drawText(); // 绘制文本，不传递context
							});
						} else {
							console.error('二维码下载失败:', qrDownloadRes);
						}
					},
					fail: (err) => console.error('二维码下载失败:', err)
				});
			},
			drawText() {
				let context = uni.createCanvasContext('canvasOne', this); // 每次绘制时重新创建context
				context.setFontSize(14);
				const nameY = this.canvasHeight - 60;
				const nameWidth = 200;

				// 在绘制文本之前打印上下文信息
				console.log('绘制文本前的context状态:', context);

				// const nameWidth = context.measureText(this.userName).width;
				context.fillText(this.userName, (this.screenWidth * 0.7 - nameWidth) / 2, nameY);

				context.draw(true, () => { // 强制同步绘制
					console.log('文本绘制完成，准备转换画布为图像...');
					this.convertCanvasToImage(); // 转换画布为图像，不传递context
				});
			},
			convertCanvasToImage() {
				let context = uni.createCanvasContext('canvasOne', this); // 每次绘制时重新创建context
				context.draw(true, () => {
					console.log("绘制完成，准备转换为临时文件...");
					uni.canvasToTempFilePath({
						destWidth: Math.round(this.screenWidth * 0.7),
						destHeight: Math.round(this.canvasHeight),
						canvasId: 'canvasOne',
						fileType: 'jpg',
						success: (res) => {
							console.log("转换成功:", res.tempFilePath);
							// uni.previewImage({
							// 	urls: [res.tempFilePath],
							// 	longPressActions: {
							// 		itemList: ['保存图片'],
							// 		success: () => {},
							// 		fail: (err) => console.error('长按保存失败:', err)
							// 	}
							// });
						},
						fail: (err) => {
							console.error('转换画布为临时文件失败:', err);
						}
					});
				});
			}
		}
	};
</script>

<style lang="scss">
	@import '@/uni.scss';

	.poster-popup {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 1000;

		canvas {
			width: 70vw;
			height: calc(70vw * 0.5);
			/* 根据宽高比计算高度 */
		}
	}
</style>